#include "yaml_cpp_utils.h"

#include <fstream>
#include <iostream>
#include <yaml-cpp/node/node.h>
#include <yaml-cpp/node/parse.h>
#include <yaml-cpp/yaml.h>

void write_yaml();
void read_yaml();

int main(int argc, char *argv[])
{
    write_yaml();
    read_yaml();
    return 0;
}

void write_yaml()
{
    YAML::Node config;
    config["server"]["host"]    = "127.0.0.1";
    config["server"]["port"]    = 10086;
    config["mysql"]["username"] = "admin";
    config["mysql"]["password"] = "password";

    YAML::Node node  = YAML::Load("[jack, rose, tom, jerry]");
    config["string"] = node;

    YAML::Node listNode;
    for (int i = 0; i < 10; i++) {
        listNode.push_back(100 + i + 1);
    }
    config["list"] = listNode;

    std::ofstream ofile("./config.yaml");
    ofile << config;
    ofile.close();
}

void read_yaml()
{
    YAML::Node config = YAML::LoadFile("./config.yaml");

    std::cout << "config size: " << config.size() << std::endl;
    for (const auto &node : config) {
        std::cout << "node name: " << node.first.as<std::string>() << std::endl;
    }

    std::string host;
    int         port;

    checkNodeExists(config, "server");
    host = getRequireValue<std::string>(config["server"], "host", "127.0.0.1");
    std::cout << "host: " << host << std::endl;

    port = getRequireValue<uint16_t>(config["server"], "port", 10086);
    std::cout << "port: " << port << std::endl;

    // 判断不存在的节点
    checkNodeExists(config, "client");

    for (int i = 0; i < config["string"].size(); i++) {
        std::cout << "str[" << i << "]: " << config["string"][i] << std::endl;
    }

    for (auto node : config["list"]) {
        std::cout << "list: " << node.as<int>() << std::endl;
    }
}